import paramiko
import pandas as pd
import tkinter as tk
import os

class SSH(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)

        # 创建窗口
        self.title("SSH批量执行工具")
        self.geometry('800x600')
        self.minsize(400,300)  # 最小尺寸
        self.maxsize(800,600)  # 最大尺寸

        ####标题####第一行####
        lb0 = tk.Label(self, text='SSH批量执行工具', font=('黑体', 24))
        lb0.place(relx=0.1, rely=0.02, relwidth=0.8, relheight=0.1)

        # 创建打开文件按钮和开始执行按钮
        open_button = tk.Button(self, text="创建模板", command=self.create_file)
        open_button.place(relx=0.72, rely=0.18, relwidth=0.15, relheight=0.08)

        open_button = tk.Button(self, text="编辑模板", command=self.open_file)
        open_button.place(relx=0.72, rely=0.3, relwidth=0.15, relheight=0.08)

        start_button = tk.Button(self, text="开始执行", command=self.start_execution)
        start_button.place(relx=0.72, rely=0.42, relwidth=0.15, relheight=0.08)

        openlog1 = tk.Button(self, text='打开日志', command=self.openlog)
        openlog1.place(relx=0.72, rely=0.54, relwidth=0.15, relheight=0.08)

        dellog1 = tk.Button(self, text='删除日志', command=self.dellog)
        dellog1.place(relx=0.72, rely=0.66, relwidth=0.15, relheight=0.08)

        ztxtdel = tk.Button(self, text='清空输出', command=self.txtdel)
        ztxtdel.place(relx=0.72, rely=0.78, relwidth=0.15, relheight=0.08)


        # 创建状态标签
        self.txt = tk.Text(self)
        self.txt.insert(0.0,
                "工具执行过程中会卡顿并无回显，请不要多次点击，耐心等待执行完成。\n")
        self.txt.place(relx=0.1, rely=0.18, relwidth=0.6, relheight=0.72)

        by = tk.Label(self, text='version：1.2  |  by:背包的小迟')
        by.place(relx=0.7, rely=0.93, relwidth=0.3, relheight=0.05)

    # SSH执行主函数
    def ssh_command(self,ip, username, password, command):
        print("正在处理主机：%s" % ip)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        print("-------------------------------------------------------------------------------", file=self.log)
        print("正在处理...host:%s\n" % ip,file=self.log)  # 输出正在处理的主机信息到日志
        print("-------------------------------------------------------------------------------", file=self.log)

        self.txt.insert(tk.END, "-------------------------------------------------------------------\n")
        self.txt.insert(tk.END, "host:%s\n" % ip)  # 输出正在处理的主机信息到对话框
        self.txt.insert(tk.END, "-------------------------------------------------------------------\n")
        try:
            # 尝试通过用户名及密码登陆服务器
            ssh.connect(hostname=ip, port=22, username=username, password=password, timeout=2)
            comm = command.split("\n")
            self.txt.insert(tk.END, "执行结果：\n")
            print("执行结果：", file=self.log)
            for com in comm:
                stdin, stdout, stderr = ssh.exec_command(com)  #执行语句
                # 读取返回内容
                fh = stdout.read()
                self.txt.insert(tk.END, com + '\n')
                self.txt.insert(tk.END, fh)
                #fh = str(fh)
                print(com,file=self.log)
                print(fh, file=self.log)

        except:
            # 连接失败或密码错误
            self.txt.insert(tk.END, "连接失败 \n")
            print("连接失败", file=self.log)

        # 关闭SSH连接
        ssh.close()
    
    def openlog(self):
        try:
            os.startfile('log\ssh_log.txt')
        except:
            self.txt.insert(tk.END, "打开失败，文件不存在 \n")


    def dellog(self):
        try:
            os.remove('log\ssh_log.txt')
            self.txt.insert(tk.END, "删除成功\n")
        except:
            self.txt.insert(tk.END, "删除失败，文件不存在 \n")
    
    def txtdel(self):  # 清空输出
        self.txt.delete(1.0, "end")  # 清空输出

    #模板创建
    def create_file(self):
        if os.path.isfile('servers.xlsx'):
            self.txt.insert(tk.END, "模板已存在\n")
        else:
            df = pd.DataFrame(columns=['ip', 'username', 'password', 'command'])
            df.to_excel('servers.xlsx', index=False)
            self.txt.insert(tk.END, "模板已创建\n")

    #编辑模板
    def open_file(self):
        os.startfile('servers.xlsx')

    #开始执行
    def start_execution(self):
        print("开始执行")
        df = pd.read_excel("servers.xlsx",sheet_name='Sheet1')
        self.txt.delete(1.0, "end")  # 清空输出
        self.log = open('log/ssh_log.txt', 'a')
        for index, row in df.iterrows():
            ip = row['ip']
            username = row['username']
            password = row['password']
            command = row['command']
            print(ip+username+password+command)
            self.ssh_command(ip, username, password, command)
        # 关闭文件写入
        self.log.close()

if __name__ == "__main__":
    os.startfile()
